package com.github.pig.admin.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pig.admin.common.util.TreeUtil;
import com.github.pig.admin.model.dto.MenuTree;
import com.github.pig.admin.model.entity.SysMenu;
import com.github.pig.admin.model.entity.SysQuickMenu;
import com.github.pig.admin.service.sys.ISysQuickMenuService;
import com.github.pig.admin.service.sys.SysMenuService;
import com.github.pig.admin.service.sys.SysUserService;
import com.github.pig.admin.util.AjaxJson;
import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.util.R;
import com.github.pig.common.vo.MenuVO;
import com.github.pig.common.vo.UserVO;
import com.github.pig.common.web.BaseController;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lengleng
 * @date 2017/10/31
 */
@RestController
@RequestMapping("/menu")
public class MenuController extends BaseController {
    @Autowired
    private SysMenuService sysMenuService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private ISysQuickMenuService quickMenuService;

    /**
     * 通过角色名称查询用户菜单
     *
     * @param role 角色名称
     * @return 菜单列表
     */
    @GetMapping("/findMenuByRole/{role}")
    public List<MenuVO> findMenuByRole(@PathVariable String role) {
        return sysMenuService.findMenuByRoleName(role);
    }

    /**
     * 返回当前用户的树形菜单集合
     * @return 当前用户的树形菜单
     */
    @GetMapping(value = "/userMenu")
    public List<MenuTree> userMenu(){
        Claims claims = getCurrentUserInfo();
        String currentUserName = (String) claims.get("user_name");
        EntityWrapper entityWrapper = new EntityWrapper();
        //获取当前登陆人 如果是admin 则展示所有菜单
        if(!CommonConstant.MANAGE_NAME.equals(currentUserName)){
            UserVO userVO = sysUserService.findUserByUsername(currentUserName);
            return sysMenuService.findUserMenuTree(userVO.getUserId());
        }
        entityWrapper.eq(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
        entityWrapper.eq("type",CommonConstant.MENU);
        entityWrapper.orderBy("sort",true);
        return getMenuTree(sysMenuService.selectList(entityWrapper), -1);
    }

    /**
     * 返回树形菜单集合
     *
     * @return 树形菜单
     */
    @GetMapping(value = "/allTree")
    public List<MenuTree> getTree() {
        Claims claims = getCurrentUserInfo();
        String currentUserName = (String) claims.get("user_name");
        EntityWrapper entityWrapper = new EntityWrapper();
        //获取当前登陆人 如果是admin 则展示所有菜单
        if(!CommonConstant.MANAGE_NAME.equals(currentUserName)){
            //不是admin，则展示admin分配给的权限
            List<MenuVO> menus = sysMenuService.findMenuByRoles(getRole());
            List<SysMenu> sysMenus = new ArrayList<>();
            for(MenuVO menuVO:menus){
                SysMenu sysMenu = new SysMenu();
                sysMenu.setMenuId(menuVO.getMenuId());
                sysMenu.setPermission(menuVO.getPermission());
                sysMenu.setParentId(menuVO.getParentId());
                sysMenu.setComponent(menuVO.getComponent());
                sysMenu.setName(menuVO.getName());
                sysMenu.setUrl(menuVO.getUrl());
                sysMenu.setPath(menuVO.getPath());
                sysMenu.setIcon(menuVO.getIcon());
                sysMenus.add(sysMenu);
            }
            return getMenuTree(sysMenus, -1);
        }
        entityWrapper.eq(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
        return getMenuTree(sysMenuService.selectList(entityWrapper), -1);
    }

    /**
     * 返回当前用户树形菜单集合
     *
     * @return 树形菜单
     */
    @GetMapping("/userTree")
    public List<Integer> userTree() {
        List<MenuVO> menus = sysMenuService.findMenuByRoles(getRole());
        List<Integer> menuList = new ArrayList<>();
        for (MenuVO menuVo : menus) {
            menuList.add(menuVo.getMenuId());
        }
        return menuList;
    }

    /**
     * 返回角色的菜单集合
     *
     * @param roleName 角色名称
     * @return 属性集合
     */
    @GetMapping("/roleTree/{roleName}")
    public List<Integer> roleTree(@PathVariable String roleName) {
        List<MenuVO> menus = sysMenuService.findMenuByRoleName(roleName);
        List<Integer> menuList = new ArrayList<>();
        for (MenuVO menuVo : menus) {
            menuList.add(menuVo.getMenuId());
        }
        return menuList;
    }

    /**
     * 通过ID查询菜单的详细信息
     *
     * @param id 菜单ID
     * @return 菜单详细信息
     */
    @GetMapping("/{id}")
    public SysMenu menu(@PathVariable Integer id) {
        return sysMenuService.selectById(id);
    }

    /**
     * 新增菜单
     *
     * @param sysMenu 菜单信息
     * @return success/false
     */
    @PostMapping
    public R<Boolean> menu(@RequestBody SysMenu sysMenu) {
        return new R<>(sysMenuService.insert(sysMenu));
    }

    /**
     * 删除菜单
     *
     * @param id 菜单ID
     * @return success/false
     * TODO  级联删除下级节点
     */
    @DeleteMapping("/{id}")
    public R<Boolean> menuDel(@PathVariable Integer id) {
        return new R<>(sysMenuService.deleteMenu(id));
    }

    @PutMapping
    public R<Boolean> menuUpdate(@RequestBody SysMenu sysMenu) {
        return new R<>(sysMenuService.updateMenuById(sysMenu));
    }

    private List<MenuTree> getMenuTree(List<SysMenu> menus, int root) {
        List<MenuTree> trees = new ArrayList<MenuTree>();
        MenuTree node;
        for (SysMenu menu : menus) {
            node = new MenuTree();
            node.setId(menu.getMenuId());
            node.setParentId(menu.getParentId());
            node.setName(menu.getName());
            node.setUrl(menu.getUrl());
            node.setPath(menu.getPath());
            node.setCode(menu.getPermission());
            node.setLabel(menu.getName());
            node.setType(menu.getType());
            node.setComponent(menu.getComponent());
            node.setIcon(menu.getIcon());
            trees.add(node);
        }
        return TreeUtil.bulid(trees, root);
    }

    @RequestMapping("/getQuickMenu")
    public List<SysMenu> getQuickMenu() {
        Claims claims = getCurrentUserInfo();
        String currentUserName = (String) claims.get("user_name");
        UserVO userVO = sysUserService.findUserByUsername(currentUserName);
        return sysMenuService.getQuickMenu(userVO.getUserId());
    }

    @RequestMapping("/getMenuByCurrentUser")
    public List<MenuTree> getMenuByCurrentUser() {
        Claims claims = getCurrentUserInfo();
        String currentUserName = (String) claims.get("user_name");
        UserVO userVO = sysUserService.findUserByUsername(currentUserName);
        List<SysMenu> list = sysMenuService.getMenuByCurrentUser(userVO.getUserId());
        return getMenuTree(list,-1);

    }
    @RequestMapping("/saveQuickMenu")
    public AjaxJson saveQuickMenu(String menuIds){
        AjaxJson json = new AjaxJson();
        json.setSuccess(true);
        Claims claims = getCurrentUserInfo();
        String currentUserName = (String) claims.get("user_name");
        UserVO userVO = sysUserService.findUserByUsername(currentUserName);
        List<SysQuickMenu> quickMenus = new ArrayList<>();
        if(menuIds!=null){
            String[] menuIdArr = menuIds.split(",");
            for(String id : menuIdArr){
                SysQuickMenu sysQuickMenu = new SysQuickMenu();
                sysQuickMenu.setMenuId(Integer.valueOf(id));
                sysQuickMenu.setUserId(userVO.getUserId());
                quickMenus.add(sysQuickMenu);
            }
            if(quickMenus!=null&&quickMenus.size()>0){
                EntityWrapper entityWrapper = new EntityWrapper();
                entityWrapper.eq("user_id",userVO.getUserId());
                quickMenuService.delete(entityWrapper);
                quickMenuService.insertBatch(quickMenus);
            }
        }else{
            json.setSuccess(false);
        }

        return json;
    }
}
